package com.api.gbhg.liuwenbo.api;

import com.alibaba.fastjson.JSON;
import com.api.gbhg.liuwenbo.dao.DataBaseUtil;
import com.api.gbhg.liuwenbo.dao.NonCentralTreeDBUtil;
import com.api.gbhg.liuwenbo.dao.TreeStuctureDBUtil;
import com.api.gbhg.liuwenbo.pojo.TreeStucture;
import com.api.gbhg.liuwenbo.pojo.TreeStuctureSenior;
import com.api.gbhg.zengping.dao.PropertyManagementCostDao;
import com.google.common.base.Joiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.file.Prop;
import weaver.general.BaseBean;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.*;

/**
 * @Description 中央组织架构
 * @Author lwb
 */

@Path("gb/TreeStucture")
public class TreeStuctureApi {

    private static final Logger LOGGER = LoggerFactory.getLogger("gbhg");

    private PropertyManagementCostDao rmcd=new PropertyManagementCostDao();

    private String tableNameKm = "uf_zyczbksr_km";
    private String tableNameXj = "uf_zyczbksr_xj";
    private static List<String> sysadmin ;
    private static List<String> status1 ;
    private static List<String> status2 ;
    private static List<String> status3 ;
    private static List<String> DepartmentStatus ;
    private static String leaderStr ;
    private BaseBean baseBean = new BaseBean();


    static{
//        BaseBean baseBean = new BaseBean();
//        sysadmin = baseBean.getPropValue("TreeStucture","sysadmin");
//        DepartmentStatus = Arrays.asList(baseBean.getPropValue("TreeStucture","DepartmentStatus").split(","));
//        status1 = Arrays.asList(baseBean.getPropValue("TreeStucture","status1").split(","));
//        status2 = Arrays.asList(baseBean.getPropValue("TreeStucture","status2").split(","));
//        status3 = Arrays.asList(baseBean.getPropValue("TreeStucture","status3").split(","));
//        leaderStr = baseBean.getPropValue("TreeStucture","leaderStr");

    }

    /**
     * 获取权限配置文件值
     */
    public void getJurisdiction(){
        sysadmin = Arrays.asList(Prop.getPropValue("TreeStucture","sysadmin"));
        DepartmentStatus = Arrays.asList(Prop.getPropValue("TreeStucture","DepartmentStatus").split(","));
        status1 = Arrays.asList(Prop.getPropValue("TreeStucture","status1").split(","));
        status2 = Arrays.asList(Prop.getPropValue("TreeStucture", "status2").split(","));
        status3 = Arrays.asList(Prop.getPropValue("TreeStucture","status3").split(","));
        leaderStr = Prop.getPropValue("TreeStucture","leaderStr");
    }


    /**
     * 暂时作废
     * @param param
     * @return
     */
    @POST
    @Path("/AddNfDw")
    @Produces(MediaType.APPLICATION_JSON)
    public String AddNfDw(Map<String,Object> param){
        Integer grade = (Integer) param.get("grade");
        String isSuccess;
        if(grade==1){
            //添加年份
            boolean is = addNf(param);
            isSuccess = String.valueOf(is);
        }else{
            //添加单位
            boolean is = adddw(param);
            isSuccess = String.valueOf(is);
        }
        return JSON.toJSONString(isSuccess);
    }

    public boolean addNf(Map<String,Object> param){
        String nf = param.get("nf").toString();
        RecordSet rs = new RecordSet();
        String sql = " select * from uf_zyczbknfdwb where srnf = "+nf+"";
        rs.executeQuery(sql);
        if (rs.getCounts()>0){
            return false;
        }else{
            String istSql = " insert into uf_zyczbknfdwb(srnf) values("+nf+") ";
            boolean issuccess = rs.executeUpdate(istSql);
            return issuccess;
        }
    }

    public boolean adddw(Map<String,Object> param){
        String nf = param.get("nf").toString();
        RecordSet rs = new RecordSet();
        String sql = " select * from uf_zyczbknfdwb where srnf = "+nf+"";
        rs.executeQuery(sql);
        boolean is = false;
        String id = "";
        while (rs.next()){
            if (rs.getString("srnf").isEmpty()){
                is = true;
                id = rs.getString("id");
                break;
            }
        }
        if (is){
            String istSql = " update uf_zyczbknfdwb set dw = "+param.get("dw").toString()+" where id = "+id+" ";
            boolean issuccess = rs.executeUpdate(sql);
            return issuccess;
        }else{
            String istSql = " insert into uf_zyczbknfdwb(srnf,dw) values("+nf+","+param.get("dw").toString()+") ";
            boolean issuccess = rs.executeUpdate(sql);
            return issuccess;
        }
    }
    //-----------------------------------------------------------------------------------------------------------------------------

    /**
     * 添加结构
     * @param param
     * @return
     */
    @POST
    @Path("/AddStucture")
    @Produces(MediaType.APPLICATION_JSON)
    public String AddStucture(Map<String,Object> param){
        Integer grade = (Integer)param.get("grade");
        String IsSuccess = "";
        if (grade==1){
            boolean is = addKmj(param);
            IsSuccess = String.valueOf(is);
        }else{
            boolean is = addXj(param);
            IsSuccess = String.valueOf(is);
        }

        return JSON.toJSONString(IsSuccess);
    }

    /**
     * 添加一级科目
     * @param param
     */
    public boolean addKmj(Map<String,Object> param){
        param.remove("grade");

        String id = Iszysr_km(param, tableNameKm);
        if (!id.isEmpty()){
            boolean isSuccess = TreeStuctureDBUtil.upfzysr_km(param, id);
            return isSuccess;
        }{
            String uuid = UUID.randomUUID().toString();
            Integer modeId = DataBaseUtil.getModeId(tableNameKm);

            List<String> list = new ArrayList<>();
            String[] names =  param.keySet().toArray(new String[param.size()]);
            Object[] values = param.values().toArray();


            String modeInsertSql = DataBaseUtil.getModeInsertSql(Arrays.asList(names), tableNameKm, uuid, modeId);
            LOGGER.info("新增中央科目级sql----："+modeInsertSql);
            RecordSet rs = new RecordSet();
//        boolean IsSuccess = rs.executeQuery();
            boolean IsSuccess = rs.executeUpdate(modeInsertSql, values);
            return IsSuccess;
        }


    }

    /**
     * 校验科目是否存在
     * @param param
     * @param uf_fzysr
     * @return
     */
    public static String Iszysr_km(Map<String,Object> param,String uf_fzysr) {
        RecordSet rs = new RecordSet();
        String sql = " select * from uf_zyczbksr_km where srnf = " + param.get("srnf") + " and dw = " + param.get("dw") + " and gnkm = " + param.get("gnkm") + " ";
        rs.executeQuery(sql);
        while (rs.next()) {
            return rs.getString("id");
        }
        return "";
    }
    /**
     * 添加下级科目
     * @param param
     * @return
     */
    public boolean addXj(Map<String,Object> param){
        param.remove("grade");
        String uuid = UUID.randomUUID().toString();
        Integer modeId = DataBaseUtil.getModeId(tableNameXj);

        List<String> list = new ArrayList<>();
        String[] names =  param.keySet().toArray(new String[param.size()]);
        Object[] values = param.values().toArray();


        String modeInsertSql = DataBaseUtil.getModeInsertSql(Arrays.asList(names), tableNameXj, uuid, modeId);
        LOGGER.info("新增中央下级sql----："+modeInsertSql);
        RecordSetTrans rs = new RecordSetTrans();
        rs.setAutoCommit(false);
        boolean IsSuccess1 = false;
        boolean IsSuccessKm = false;
        boolean IsSuccessXj = false;
        try {
            IsSuccess1 = rs.executeUpdate(modeInsertSql, values);
            if(param.containsKey("szgnkm")&&param.containsKey("sjzxsr")){

                List<String> sjzxsr = TreeStuctureDBUtil.getSuperiorId(Integer.parseInt(param.get("sjzxsr").toString()));

                for (String sjId:sjzxsr) {
                    String sumSql = " select sum(yjsr) yjsr,sum(yqndyjjzje) yqndyjjzje,sum(yqndsjjzje) yqndsjjzje,sum(yjsrsy) yjsrsy," +
                            "sum(yqndyjjzsyje) yqndyjjzsyje,sum(yqndsjjzsyje) yqndsjjzsyje," +
                            "sum(yhpje) yhpje,sum(djje) djje,sum(sjbxje) sjbxje,sum(yhpsy) yhpsy,sum(yqndyjjzyyje) yqndyjjzyyje," +
                            "sum(jzyyje) jzyyje,sum(jzsyje) jzsyje,sum(yqndsjjzyyje) yqndsjjzyyje,sum(snjzje) snjzje,sum(snjzhpje) snjzhpje," +
                            "sum(snjzhpbxje) snjzhpbxje,sum(snjzhpsyje) snjzhpsyje,sum(snjzhpdjje) snjzhpdjje " +
                            " from uf_zyczbksr_xj where sjzxsr  = "+sjId+" " ;
                    rs.execute(sumSql);
                    if (rs.getCounts()>0){ //金额添加到上级
                        rs.next();
//                    String addxjjesql = TreeStuctureDBUtil.SynUpperStrataSql(param.get("sjzxsr").toString(), rs.getString("yjsr"), rs.getString("yqndyjjzje"), rs.getString("yqndsjjzje"),

                        String addxjjesql = TreeStuctureDBUtil.SynUpperStrataSql2(sjId,rs);
                        LOGGER.info("新增中央下级时 汇总到上级sql----："+modeInsertSql);
                        IsSuccessXj = rs.executeUpdate(addxjjesql);
                        if (IsSuccessXj == false)
                            break;
                    }else{
                        IsSuccessXj = true;
                    }
                }

//                boolean addxjjesql = TreeStuctureDBUtil.SynUpperStrata(param.get("sjzxsr").toString());//金额添加到上级

                String addkmjesql = TreeStuctureDBUtil.AddKmJeSql2((Integer) param.get("szgnkm"),param);//金额添加到一级
                LOGGER.info("新增中央下级时 汇总到科目级sql----："+addkmjesql);

                List<String> superiorId = TreeStuctureDBUtil.getSuperiorId((Integer) param.get("sjzxsr"));
//                String addxjjesql = TreeStuctureDBUtil.AddxjJeSql(superiorId,param,SumSql);//金额添加到上级

                IsSuccessKm = rs.executeUpdate(addkmjesql);
            }else{
                String addkmjesql = TreeStuctureDBUtil.AddKmJeSql2((Integer) param.get("szgnkm"),param);//金额添加到一级
                LOGGER.info("新增中央下级时 汇总到科目级sql----："+addkmjesql);
                IsSuccessKm = rs.executeUpdate(addkmjesql);
                IsSuccessXj = true;
            }
        } catch (Exception e) {
            rs.rollback();
            e.printStackTrace();
            return false;
        }
        if (IsSuccess1&&IsSuccessKm&&IsSuccessXj){
            rs.commit();
            return true;
        }else{
            rs.rollback();
            return false;
        }
    }

//    /**
//     * 添加下级科目
//     * @param param
//     * @return
//     */
//    public boolean addXj(Map<String,Object> param){
//        param.remove("grade");
//        String uuid = UUID.randomUUID().toString();
//        Integer modeId = DataBaseUtil.getModeId(tableNameXj);
//
//        String[] names =  param.keySet().toArray(new String[param.size()]);
//        Object[] values = param.values().toArray();
//
//
//        String modeInsertSql = DataBaseUtil.getModeInsertSql(Arrays.asList(names), tableNameXj, uuid, modeId);
//        LOGGER.info("新增中央下级sql----："+modeInsertSql);
//        RecordSetTrans rs = new RecordSetTrans();
//        rs.setAutoCommit(false);
//        boolean IsSuccess1 = false;
//        boolean IsSuccessKm = false;
//        boolean IsSuccessXj = false;
//        try {
//            IsSuccess1 = rs.executeUpdate(modeInsertSql, values);
//            if(param.containsKey("szgnkm")&&param.containsKey("sjzxsr")){
//
//
//                String addkmjesql = TreeStuctureDBUtil.AddKmJeSql((Integer) param.get("szgnkm"),param);//金额添加到一级
//                LOGGER.info("新增中央下级时 汇总到科目级sql----："+addkmjesql);
//
//                List<String> superiorId = TreeStuctureDBUtil.getSuperiorId((Integer) param.get("sjzxsr"));
////                String addxjjesql = TreeStuctureDBUtil.AddxjJeSql(superiorId,param,"");//金额添加到上级
//                String sjIds = Joiner.on(",").join((Iterable<?>) superiorId);
//                String addSjJeSql = TreeStuctureDBUtil.addSjJeSql(param.get("yjsr").toString(), param.get("yqndyjjzje").toString(),
//                        param.get("yqndsjjzje").toString(),param.get("yjsrsy").toString(), sjIds);
//                IsSuccessXj = rs.executeUpdate(addSjJeSql);
//
//
//                IsSuccessKm = rs.executeUpdate(addkmjesql);
//            }else{
//                String addkmjesql = TreeStuctureDBUtil.AddKmJeSql((Integer) param.get("szgnkm"),param);//金额添加到一级
//                LOGGER.info("新增中央下级时 汇总到科目级sql----："+addkmjesql);
//                IsSuccessKm = rs.executeUpdate(addkmjesql);
//                IsSuccessXj = true;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            rs.rollback();
//        }
//        if (IsSuccess1&&IsSuccessKm&&IsSuccessXj){
//            rs.commit();
//            return true;
//        }else{
//            rs.rollback();
//            return false;
//        }
//    }

    //---------------------------------------------------------------------------------------------------------------------------

    /**
     * 展示树结构
     * @return
     */
    @POST
    @Path("/DisplayTreeStucture")
    @Produces(MediaType.APPLICATION_JSON)
    public String DisplayTreeStucture(Map<String,Object> param){
        this.getJurisdiction();
//        Map<String, List<TreeStuctureSenior>> querynfdw = querynfdw();
//        List<TreeStuctureSenior> list = new ArrayList<>();
//        for (Map.Entry<String, List<TreeStuctureSenior>> entry: querynfdw.entrySet()){
//            list.addAll(entry.getValue());
//        }
        Map<String,Map<String,List<TreeStucture>>> map = queryTree(param);
        List<TreeStuctureSenior> list = new ArrayList<>();
        int i = 0;
        int j = 0;
        for (Map.Entry<String,Map<String,List<TreeStucture>>> entry: map.entrySet()) {
            TreeStuctureSenior tree = new TreeStuctureSenior();
            tree.setTitle(entry.getKey());
            tree.setKey(String.valueOf(i));
            List<TreeStuctureSenior> listdw = new ArrayList<>();
            for (Map.Entry<String,List<TreeStucture>> entrydw: entry.getValue().entrySet()) {
                TreeStuctureSenior treedw = new TreeStuctureSenior();
                String[] s = entrydw.getKey().split("_");
                treedw.setTitle(s[0]);
                treedw.setKey("0-"+j);
                treedw.setChildren(entrydw.getValue());
                treedw.setDwId(s[1]);
                treedw.setNf(s[2]);
                listdw.add(treedw);
                j++;
            }
            tree.setDw(listdw);
            list.add(tree);
            i++;
        }
        return JSON.toJSONString(list);
    }

    public Map<String,Map<String,List<TreeStucture>>> queryTree(Map<String,Object> param){
        RecordSet km = queryKm();
        List<TreeStuctureSenior> lists = new ArrayList<>();

        Map<String,Map<String,List<TreeStucture>>> nfmap = new LinkedHashMap<>();

        String SubComPany = "1";
        //if (((Integer)param.get("id")) != Integer.valueOf(sysadmin)){ sysadmin改为数组后调整
        if (!sysadmin.contains(param.get("id"))){
            //分部
            SubComPany = TreeStuctureDBUtil.getSubCompanyIdByUserId((Integer) param.get("id"))+"";
        }
        //部门
        String Department = TreeStuctureDBUtil.getDepartmentIdByUserId((Integer) param.get("id"));
        //矩阵
        List<String> subDefinedId = TreeStuctureDBUtil.getSubcompanyDefinedByUserId((Integer) param.get("id"));
        //下级分部
        List<String> subDivisionList = TreeStuctureDBUtil.getSupSubcomIdByUserId((Integer) param.get("id"), leaderStr);


        int z = 0;
        String uid = param.get("id").toString();
        if (sysadmin.contains(SubComPany) || DepartmentStatus.contains(Department) || status1.contains(uid)){

        }else if (DataBaseUtil.isAuthorityByUid(uid)){
            String bmid = DataBaseUtil.getAuthoritySubIdByUid(uid);
            String sql = " select * from "+tableNameKm+" where dw in ("+bmid+")  order by srnf desc ";
            km.executeQuery(sql);
        }else if (status3.contains(uid)){
            
        }else{
            return nfmap;
        }


        for (int i = 0 ; i< km.getCounts() ; i++){
            km.next();

//            if (SubComPany != Integer.valueOf(sysadmin) && !DepartmentStatus.contains(Department) &&
//                    !status1.contains(uid) && !status2.contains(uid) && !status3.contains(uid) && !subDefinedId.contains(km.getString("dw"))){
//                if (subDivisionList.isEmpty()){
//                    continue;
//                }else{
//                    if (!subDivisionList.contains(km.getString("dw"))){
//                        continue;
//                    }
//                }
//            }


            List<TreeStucture> listTree = new ArrayList<>();
            TreeStucture tree = new TreeStucture();

            tree.setTitle(km.getString("kmdm"));
            tree.setKey("0-0-"+i);
            List<TreeStucture> list = TreeStuctureDBUtil.children(km.getInt("id"), i,tableNameXj);
            if (list.isEmpty()){
                tree.setLeaf(false);
            }else{
                tree.setLeaf(true);
                tree.setChildren(list);
            }
            String srnf = km.getString("srnf");
            tree.setSrnf(srnf+"年部门预算");
            tree.setId(km.getString("id"));
            tree.setKmdm(km.getString("kmdm"));
            tree.setKmmc(km.getString("gnkmmc"));
            tree.setYqndsjjzje(km.getString("yqndsjjzje"));
            tree.setYqndyjjzje(km.getString("yqndyjjzje"));
            tree.setYjsr(km.getString("yjsr"));
            tree.setYhpje(km.getString("yhpje"));
            tree.setYjsrsy(km.getString("yjsrsy"));
            tree.setDjje(km.getString("djje"));
            tree.setSjbxje(km.getString("sjbxje"));
            tree.setSnjzje(km.getString("snjzje"));
            tree.setJzyyje(km.getString("jzyyje"));
            tree.setJzsyje(km.getString("jzsyje"));
            tree.setYqndyjjzsyje(km.getString("yqndyjjzsyje"));
            tree.setYqndsjjzsyje(km.getString("yqndsjjzsyje"));
            int dwid = km.getInt("dw");
            tree.setDwId(String.valueOf(dwid));
            RecordSet dw = rmcd.getSBDWById(dwid);
            dw.next();
            String dwStr = dw.getString("SUBCOMPANYNAME");
            tree.setDw(dwStr);
            listTree.add(tree);
            String dwname_Id = dwStr+"_"+dwid+"_"+srnf;
            if (nfmap.containsKey(tree.getSrnf())){
                if (nfmap.get(tree.getSrnf()).containsKey(dwname_Id)){
                    nfmap.get(tree.getSrnf()).get(dwname_Id).add(tree);
                }else{
                    nfmap.get(tree.getSrnf()).put(dwname_Id,listTree);
                }
            }else{
                Map<String,List<TreeStucture>> dwMap = new HashMap<>();
                dwMap.put(dwname_Id,listTree);
                nfmap.put(tree.getSrnf(),dwMap);
            }
        }
        return nfmap;
    }



    /**
     * 查询一级科目
     * @return
     */
    public RecordSet queryKm(){
        RecordSet rs = new RecordSet();
        String sql = " select * from "+tableNameKm+"  order by srnf desc ";
        rs.executeQuery(sql);
        return rs;
    }

    //--------------------------------------------------------------------------------------------------------------------------
    /**
     * 获取科目代码
     * @param param
     * @return
     */
    @POST
    @Path("/getGnkmDm")
    @Produces(MediaType.APPLICATION_JSON)
    public String getGnkmDm(Map<String,Object> param){
        Integer id = (Integer)param.get("id");
        return JSON.toJSONString(TreeStuctureDBUtil.getGnkmDm(id));
    }


    //----------------------------------------------------------------------------------------------------------------------------删除

    @POST
    @Path("/deleteTree")
    @Produces(MediaType.APPLICATION_JSON)
    public String deleteTree(Map<String,Object> param){
        Integer grade = (Integer)param.get("grade");
        boolean IsSuccess = false;
        if(grade == 1){
            IsSuccess = TreeStuctureDBUtil.deleteKm(param.get("id").toString());
            return JSON.toJSONString(String.valueOf(IsSuccess));
        }else{

            IsSuccess = TreeStuctureDBUtil.deleteXj(param);
            return JSON.toJSONString(String.valueOf(IsSuccess));
        }
    }

    //------------------------------------------------------------------------------------------------------------------------------------修改

    /**
     * 修改
     * @param param
     * @return
     */
    @POST
    @Path("/modifyTree")
    @Produces(MediaType.APPLICATION_JSON)
    public String modifyTree(Map<String,Object> param){
        Integer grade = (Integer) param.get("grade");
        String isSuccess;
        if (grade==1){
            boolean is = TreeStuctureDBUtil.modifyzysr_km(param,tableNameKm);
            isSuccess = String.valueOf(is);
        }else{
            boolean is = TreeStuctureDBUtil.modifyzysr_xj(param,tableNameXj);
            isSuccess = String.valueOf(is);
        }
        return JSON.toJSONString(isSuccess);
    }



    //------------------------------------------------------------------------------------------------------------------------------------调整


    @POST
    @Path("/updateTree")
    @Produces(MediaType.APPLICATION_JSON)
    public String updateTree(Map<String,Object> param){
        Integer grade = (Integer)param.get("grade");
        boolean IsSuccess = false;
        String success = "";
        if(grade == 1){
            IsSuccess = TreeStuctureDBUtil.updateKm(param);
            return JSON.toJSONString(String.valueOf(IsSuccess));
        }else{

            IsSuccess = TreeStuctureDBUtil.updateXj2(param);
            return JSON.toJSONString(String.valueOf(IsSuccess));
        }
    }


    //------------------------------------------------------------------------------------------------------------------------------------查看日志

    /**
     *查看修改日志
     * @param param
     * @return
     */
    @POST
    @Path("/queryLog")
    @Produces(MediaType.APPLICATION_JSON)
    public String queryLog(Map<String,Object> param){
        Integer grade = (Integer) param.get("grade");
        List<String> logList ;
        if (grade == 1){ //一级
            logList = getLogYj(param);
        }else{
            logList = getLogXj(param);
        }
        return JSON.toJSONString(logList);
    }

    public List<String> getLogYj(Map<String,Object> param){
        List<String> list = new ArrayList<>();
        RecordSet rs = new RecordSet();
        String sql = "  select * from uf_zyczbksrtz where dzdygnkm = "+param.get("id")+" ";
        rs.executeQuery(sql);
        while (rs.next()){
            list.add("名称："+rs.getString("mc")+"; 调整原因："+rs.getString("dzyy")+"; 调整日期"+rs.getString("dzrq")+"; 调整金额"+rs.getString("dzjey"));
        }
        return list;
    }

    public List<String> getLogXj(Map<String,Object> param){
        List<String> list = new ArrayList<>();
        List<String> id = TreeStuctureDBUtil.getXj(param.get("id").toString());
        id.add(param.get("id").toString());
        RecordSet rs = new RecordSet();
        String sql = " select * from uf_zyczbksrtz where dzdyzxsr in ("+ Joiner.on(",").join((Iterable<?>) id) +")  ";
        rs.executeQuery(sql);
        while (rs.next()){
            list.add("名称："+rs.getString("mc")+"; 调整原因："+rs.getString("dzyy")+"; 调整日期"+rs.getString("dzrq")+"; 调整金额"+rs.getString("dzjey"));
        }
        return list;
    }

}
